package com.schoolcloud.front.controller;

import cn.hutool.core.util.StrUtil;
import com.schoolcloud.common.model.FrontUserLoginDTO;
import com.schoolcloud.common.model.PageDTO;
import com.schoolcloud.common.model.R;
import com.schoolcloud.common.model.UserInfo;
import com.schoolcloud.common.util.UserContext;
import com.schoolcloud.front.entity.FroUser;
import com.schoolcloud.front.query.FroUserQuery;
import com.schoolcloud.front.service.FroUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/front/user")
@RequiredArgsConstructor
public class FroUserController {
    private final FroUserService froUserService;

    @GetMapping("/{userId}")
    public R<FroUser> getUserById(@PathVariable String userId) {
        FroUser byId = froUserService.getById(userId);
        return R.ok(byId);
    }
    @GetMapping("/info/{userId}")
    public R<UserInfo> getUserInfo(@PathVariable Integer userId) {
        UserInfo froUserInfo =froUserService.getUserInfo(userId);
        return R.ok(froUserInfo);
    }
    @PostMapping("/login")
    public R<FroUser> login(@RequestBody FrontUserLoginDTO froUser){
        return R.ok(froUserService.login(froUser));
    }
    @GetMapping
    public R<FroUser> getUser(FroUser froUser) {
        String userId = froUser.getUserId().toString();
        String userName = froUser.getUserName();
        String phone = froUser.getPhone();
        FroUser byId = froUserService.lambdaQuery().eq(StrUtil.isNotBlank(userId), FroUser::getUserId, userId)
                .eq(StrUtil.isNotBlank(userName), FroUser::getUserName, userName)
                .eq(StrUtil.isNotBlank(phone), FroUser::getPhone, phone).one();
        return R.ok(byId);
    }

    @GetMapping("by/login")
    public R<FroUser> getUserByLogin() {
        FroUser byId = froUserService.getById(UserContext.getUser());
        return R.ok(byId);
    }

    @GetMapping("/page")
    public R<PageDTO<FroUser>> getUserQuery(FroUserQuery query) {
        PageDTO<FroUser> page = froUserService.getUserQuery(query);
        return R.ok(page);
    }

    @PostMapping
    public R<String> saveUser(@RequestBody FroUser froUser) {
        froUser.setCreateTime(LocalDateTime.now());
        froUserService.save(froUser);
        return R.ok("保存成功",null);
    }
    @GetMapping("/info/by-login")
    public R<UserInfo> getLoginUserInfo(){
        UserInfo froUserInfo =froUserService.getUserInfo(UserContext.getUserToInteger());
        return R.ok(froUserInfo);
    }
    @PutMapping("/by/login-user")
    public R<?> updateUser(@RequestBody FroUser froUser) {
        froUserService.updateById(froUser);
        return R.ok("更新成功",null);
    }
}
